<template>
	<a-modal :title="title" :visible="visible" :confirmLoading="loading" @ok="ok" @cancel="cancel" width="700px" centered destroyOnClose :maskClosable="false" wrapClassName="a-modal-dialog">
		<div class="grant-container">
			<a-form ref="formRef" :model="formState" name="basic" :label-col="{span: 6}" :wrapper-col="{span: 18}" autocomplete="off" labelAlign="left">
				<a-form-item label="被授权人姓名" name="name" :rules="[{required: true, message: '请输入被授权人姓名'}]">
					<a-input disabled v-model:value="formState.name" placeholder="请输入被授权人姓名" />
				</a-form-item>
				<a-form-item label="被授权人电话" name="phone" :rules="[{required: true, message: '请输入被授权人电话'}]">
					<a-input disabled v-model:value="formState.phone" placeholder="请输入被授权人电话" />
				</a-form-item>
				<a-form-item label="设备类型" name="deviceType" :rules="[{required: true, message: '请选择设备类型'}]">
					<a-select v-model:value="formState.deviceType" :options="deviceOptions" placeholder="请选择设备类型" allowClear />
				</a-form-item>
				<a-form-item label="授权类型" name="type" :rules="[{required: true, message: '请选择授权类型'}]">
					<a-select v-model:value="formState.type" :options="typeOptions" placeholder="请选择授权类型" allowClear />
					<div v-if="formState.deviceType === 1 && [AUTH_TYPE_IC, AUTH_TYPE_FP].includes(formState.type) && !isElectron">
						<a-button shape="round" style="margin-top: 12px" @click="download">
							<template #icon>
								<DownloadOutlined />
							</template>
							点击下载客户端（仅支持 windows 系统）
						</a-button>
					</div>
				</a-form-item>
				<a-form-item label="指纹录入状态" v-if="formState.deviceType === 1 && formState.type === AUTH_TYPE_FP">
					<a-space>
						<a-button type="primary" :disabled="!isElectron" @click="addFp($event,isD5Fp)">{{ isElectron ? '录入' : '请在客户端操作' }}</a-button>
						<div>{{ fpState.fpMsg }}</div>
					</a-space>
				</a-form-item>
				<a-form-item label="授权开卡" v-if="formState.deviceType === 1 && formState.type === AUTH_TYPE_IC">
					<a-space>
						<a-button type="primary" :disabled="!isElectron" @click="readCard">{{ isElectron ? '读卡' : '请在客户端操作' }}</a-button>
						<div>{{ cardData?.cardNumber || '-' }}</div>
					</a-space>
				</a-form-item>

				<a-form-item label="授权有效期" name="date" :rules="[{required: true, message: '请选择授权有效期'}]">
					<a-range-picker v-model:value="formState.date" :show-time="showTime" :disabled-date="disabledDate" class="date-picker" />
				</a-form-item>
			</a-form>
		</div>
	</a-modal>
</template>
<script setup lang="ts">
	import {computed, reactive, ref, watch} from 'vue'
	import {message} from 'ant-design-vue'
	import {grantTenantBleKey, sendGrantTenantPwd, sendGrantTenantPwdWithoutCenter} from '@/api/lock'
	import {getAssociatedDevice} from '@/api/house'
	import {grantTenantAccessAuth} from '@/api/device'
	import {isD3B, isNBLock, isD5FpLock} from '@/utils/device'
	import dayjs, {Dayjs} from 'dayjs'
	import '@/utils/dll'
	import {AUTH_TYPE_BLUE, AUTH_TYPE_FP, AUTH_TYPE_IC, AUTH_TYPE_PWD} from './const'
	import {download, getTypeOptions, isElectron, useCardModule, useFingerPrintModule, useRenter} from './grant-utils'

	const props = defineProps<{
		visible: any
		accessDetail: any
	}>()
	const {cardData, readCard, resetCardData, handleAccessByCard} = useCardModule()
	const {handleAccessFingerPrint, resetFpData, fpState, addFp} = useFingerPrintModule()
	const {renterInfo, getRenter} = useRenter()

	const emit = defineEmits(['update:visible', 'success'])
	const visible = computed(() => {
		return !!props.visible
	})

	const title = computed(() => {
		return '新增授权'
	})

	const formState = ref<any>({
		type: null,
		name: '',
		phone: '',
		deviceType: 1,
		date: []
	})

	const GateOptions = [
		{value: 1, label: '人脸'},
		{value: 2, label: '手机开门'}
	]
	let lockOptions: any = reactive([])
	const typeOptions = computed(() => {
		return formState.value.deviceType === 1 ? lockOptions : GateOptions
	})

	const deviceInfo: any = ref([])
	const lockDevice = computed(() => deviceInfo.value.find((e: any) => e.deviceType === 5) || {})
	const gateDevice = computed(() => deviceInfo.value.find((e: any) => e.deviceType === 6) || {})
	const deviceOptions = computed(() => {
		const res: any = []
		if (lockDevice.value.sn) res.push({value: 1, label: '门锁'})
		if (gateDevice.value.sn) res.push({value: 2, label: '门禁'})
		return res
	})

	const isNB = computed(() => {
		return isNBLock(lockDevice.value?.sn)
	})

	const isD5Fp = computed(() => {
		return isD5FpLock(lockDevice.value?.sn)
	})

	const isD3BLock = computed(() => {
		return isD3B(lockDevice.value?.sn)
	})

	const isOfflinePwd = computed(() => {
		if (formState.value.type !== AUTH_TYPE_PWD) return false
		if (isNB.value) return false
		if (isD3BLock.value) return true
		return lockDevice.value?.online !== 1
	})

	// lock

	const showTime = {
		defaultValue: ['', dayjs('23:59:59', 'HH:mm:ss')]
	}

	const disabledPastTime = (current: Dayjs) => {
		return current && current.endOf('day').valueOf() <= dayjs().valueOf()
	}
	const oneYear = dayjs().add(1, 'year').valueOf()
	const disabledAfterOneYear = (current: Dayjs) => {
		return current && current.endOf('day').valueOf() > oneYear
	}

	const disabledDate = (current: Dayjs) => {
		let {beginTime, endTime, rentFreeDay} = props.accessDetail
		console.log(props.accessDetail)
		if(rentFreeDay>0) {
			beginTime = dayjs(beginTime).subtract(rentFreeDay, 'day')
		}
		if (disabledPastTime(current)) {
			return true
		}
		if (isOfflinePwd.value && disabledAfterOneYear(current)) {
			return true
		}
		if (current && beginTime && endTime) {
			if (current.valueOf() <= dayjs(beginTime).valueOf()) {
				return true
			}
			if (current.valueOf() >= dayjs(endTime).endOf('day').valueOf()) {
				return true
			}
		}
	}

	watch(
		() => props.visible,
		async (newVal: any) => {
			if (newVal) {
				const {name, phone, houseId} = props.accessDetail
				formState.value = {
					type: null,
					name,
					phone,
					date: []
				}
				initData()
			} else {
				resetData()
			}
		}
	)
	const initData = async () => {
		const {name, phone, houseId} = props.accessDetail
		const res = await getAssociatedDevice(houseId)
		deviceInfo.value = res.data

		getRenter(houseId)
		lockOptions = await getTypeOptions(lockDevice.value?.sn)
		// lockOptions = await getTypeOptions('lkjl0066220504438833')
		const hasLock = (res.data || []).some(e => e.deviceType === 5)
		const hasGate = (res.data || []).some(e => e.deviceType === 6)
		if (hasLock) formState.value.deviceType = 1
		if (hasGate) formState.value.deviceType = 2
		if (hasGate && hasLock) formState.value.deviceType = null
	}
	const cancel = () => {
		emit('update:visible', null)
		resetData()
	}
	const resetData = () => {
		resetCardData()
		resetFpData()
		formState.value = {
			type: null,
			name: '',
			phone: '',
			deviceType: null,
			date: []
		}
	}
	const loading = ref(false)
	const formRef = ref<any>()
	const ok = async () => {
		await formRef.value.validateFields()
		const {deviceType} = formState.value
		const APIMap = {
			2: handleAccessGate,
			1: handleAccessLock
		}
		APIMap && APIMap[deviceType]()
	}
	/** 门锁 */
	const handleAccessLock = async () => {
		const {name, phone, certificationType, identityCard, houseId, renterRelation} = props.accessDetail || {}
		const data: any = {
			roomId: houseId,
			scene: 8, //场景 1看房2入住3维修4保洁5配货6其他7新增同住人8租户授权
			authSource: 2, //授权来源 1:管理员密码 2:合同 3:设备 4:同住人申请 5：第三方
			name,
			phone,
			certificationType,
			identityCard,
			relateType: 1,
			relateId: renterInfo.value.id,
			renterRelation: renterRelation ? renterRelation : undefined, // 与租户关系 1配偶 2子女 3父母 4亲属 5合租人 6其他
			startTime: formState.value.date?.[0]?.format('YYYY-MM-DD HH:mm:ss'),
			endTime: formState.value.date?.[1]?.format('YYYY-MM-DD HH:mm:ss')
		}
		console.log(data)
		const successCallBack = () => {
			loading.value = false

			message.success('操作成功')
			emit('update:visible', null)
			emit('success')
			formRef.value.resetFields()
			resetData()
		}
		if (formState.value.type === AUTH_TYPE_PWD) {
			loading.value = true
			const isOnline = lockDevice.value?.online === 1
			const sendPwd = isNB.value || (isOnline && !isD3BLock.value) ? sendGrantTenantPwd : sendGrantTenantPwdWithoutCenter
			try {
				await sendPwd(data)
				successCallBack()
			} catch (error) {
				loading.value = false
			}
		}

		// 指纹
		if (formState.value.type === AUTH_TYPE_FP) {
			try {
				loading.value = true
				await handleAccessFingerPrint(data, false, isD5Fp.value)
				successCallBack()
			} catch (error) {
				loading.value = false
			}
		}

		// 卡
		if (formState.value.type === AUTH_TYPE_IC) {
			try {
				loading.value = true
				await handleAccessByCard(data)
				successCallBack()
			} catch (error) {
				loading.value = false
			}
		}
		// 蓝牙
		if (formState.value.type === AUTH_TYPE_BLUE) {
			try {
				loading.value = true
				await grantTenantBleKey(data)
				successCallBack()
			} catch (error) {
				loading.value = false
			}
		}
	}
	/** 门禁 */
	const handleAccessGate = async () => {
		const {name, phone, contractId} = props.accessDetail
		const {date, type} = formState.value
		const data = {
			phone: phone,
			name: name,
			contractId: contractId,
			authTypes: [type],
			authStart: formState.value.date?.[0]?.format('YYYY-MM-DD HH:mm:ss'),
			authEnd: formState.value.date?.[1]?.format('YYYY-MM-DD HH:mm:ss')
		}
		loading.value = true
		await grantTenantAccessAuth(data).finally(() => {
			loading.value = false
		})
		message.success('操作成功')
		emit('update:visible', null)
		emit('success')
		loading.value = false
	}
</script>
<style scoped>
	.grant-container {
		padding: 36px 60px 16px;
	}

	.id-number-col {
		padding-left: 20px;
	}

	.date-picker {
		width: 100%;
	}
</style>
